package com.ds.infrastructure.hyperspace.container.flow.handler.zone;

import com.ds.infrastructure.hyperspace.common.Container;
import com.ds.infrastructure.hyperspace.common.flow.FlowHandlerPipeline;
import com.ds.infrastructure.hyperspace.container.flow.context.HyperspaceDuplexFlowContext;
import com.ds.infrastructure.hyperspace.container.flow.handler.AbstractPreFlowHandler;
import com.ds.infrastructure.hyperspace.container.internal.operator.OperatorDefinition;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * usage eg:
 * -   handler: conditionalZonePreHandler
 * handlerParams: [bj,zoneIgnore,EQUAL,true]
 *
 * @Author: yaozh
 * @Description:
 */
public class ConditionalZonePreFlowHandler extends AbstractPreFlowHandler {
    private static final int INPUT_NAME_INDEX = 1;
    private volatile String inputName;
    private volatile String zone;
    private volatile List<OperatorDefinition> operatorDefinitionList;

    @Override
    public void handleInput(HyperspaceDuplexFlowContext duplexFlowContext, Object data) {
        if (data != duplexFlowContext.getRequestStartState() || StringUtils.isEmpty(zone)) {
            return;
        }
        if (extractAndComputeInput(duplexFlowContext, inputName, operatorDefinitionList) == null) {
            return;
        }
        duplexFlowContext.setZoneId(zone);
    }

    @Override
    public String handlerName() {
        return "conditionalZonePreHandler";
    }

    @Override
    public void initHandlerParameters(Container container, FlowHandlerPipeline pipeline, String[] handlerParams) {
        if (handlerParams.length > 0 && !StringUtils.isEmpty(handlerParams[0])) {
            zone = handlerParams[0].toLowerCase();
        }
        if (handlerParams.length > INPUT_NAME_INDEX) {
            inputName = handlerParams[INPUT_NAME_INDEX];
            operatorDefinitionList = parseOperatorDefinition(container, handlerParams, INPUT_NAME_INDEX + 1);
        }
    }
}
